package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-14
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备集合
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /*
     * 从互联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //到物联网平台查询 产品数据
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品数据失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    /*
     * 查询产品列表
     */
    @Override
    public List<ProductVo> allproduct() {
        //从redis中获取产品数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /*
     * 注册设备
     */
    @Override
    public void register(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapperName = new LambdaQueryWrapper<>();
        queryWrapperName.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapperName) > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }
        //判断设备标识码是否重复
        LambdaQueryWrapper<Device> queryWrapperNodeId = new LambdaQueryWrapper<>();
        queryWrapperNodeId.eq(Device::getNodeId, deviceDto.getNodeId());
        if (count(queryWrapperNodeId) > 0) {
            throw new BaseException("设备标识码已存在，请重新输入");
        }
        //判断同一位置是否绑定了同一类产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        if (count(condition) > 0) {
            throw new BaseException("老人/该位置已经绑定了产品，请重新选择");
        }

        //新增设备iot mysql
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        AuthInfo authInfobody = new AuthInfo();

        //UUID
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfobody.withSecret(secret);

        body.withAuthInfo(authInfobody);
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());

        request.withBody(body);

        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("物联网接口-注册设备，调用失败");
        }

        //写入到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        try {
            save(device);
        } catch (Exception e) {
            throw new RuntimeException("同一位置不能绑定同类型的产品");
        }
    }

    /*
     * 查询设备详细数据
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }
        //查询华为云
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口-查询设备详情，调用失败");
        }

        //组合数据
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotNull(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(activeTime);
        }
        return vo;
    }

    /*
     * 查询上报的数据
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        //调用iot平台接口查询数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        //如果没有数据——返回一个空集合
        if (CollUtil.isEmpty(shadow)) {
            return AjaxResult.success(Collections.emptyList());
        }
        //有数据——对数据进行处理
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        List<Map<String, Object>> list = new ArrayList<>();

        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return AjaxResult.success(list);
    }

    /*
     * 删除设备数据
     */
    @Override
    @Transactional
    public void deleteById(String iotId) {
        //删除华为云数据
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-删除设备，调用失败");
        }
        //删除数据库数据
        Device device = deviceMapper.selectById(iotId);
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        deviceMapper.deleteById(iotId);

    }

    /*
     * 修改设备
     */
    @Override
    @Transactional
    public void updateByDeviceId(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapperName = new LambdaQueryWrapper<>();
        queryWrapperName.eq(Device::getDeviceName, deviceDto.getDeviceName())
                .ne(Device::getIotId, deviceDto.getIotId());//排除自己
        if (count(queryWrapperName) > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }
        //判断同一位置是否绑定了同一类产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .ne(Device::getIotId, deviceDto.getIotId());//排除自己
        if (count(condition) > 0) {
            throw new BaseException("老人/该位置已经绑定了产品，请重新选择");
        }

        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, deviceDto.getIotId());
        Device deviceSelect = deviceMapper.selectOne(queryWrapper);

        if (deviceSelect == null) {
            throw new BaseException("设备不存在");
        }

        //修改数据库数据
        Device device = new Device();
        device.setId(deviceSelect.getId()); // 设置数据库主键
        device.setIotId(deviceDto.getIotId());
        device.setDeviceName(deviceDto.getDeviceName());// 备注名称
        device.setLocationType(deviceDto.getLocationType());// 接入类别
        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation())); // 接入位置
        device.setRemark(deviceDto.getRemark());//备注

        deviceMapper.updateDevice(device);

        //修改华为云数据-------------------------------
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());

        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        body.withAuthInfo(authInfobody);
        body.withDeviceName(deviceDto.getDeviceName());

        request.withBody(body);

        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-修改设备，调用失败");
        }
    }

}
